package com.example.demo.service.impl;

import com.example.demo.controller.bean.Result;
import com.example.demo.dto.*;
import com.example.demo.mapper.PointsMallManageMapper;
import com.example.demo.mapper.entity.*;
import com.example.demo.service.PointsMallManageService;
import com.example.demo.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PointsMallManageServiceImpl implements PointsMallManageService {
    @Autowired
    private PointsMallManageMapper mapper;

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime lastUpdatedTime = LocalDateTime.now();
    String format = lastUpdatedTime.format(formatter);

    @Override
    public PageVo<Commodity> getCommodityList(PageBo pageBo) {
        List<Commodity> logs = mapper.getCommodityList();
        return new PageVo<>(pageBo, logs);
    }

    //商品名稱，分類
    @Override
    public PageVo<Commodity> searchCommodityList(CommodityRequestDTO request, PageBo pageBo) {
        String commodityName=request.getCommodityName();
        int category=request.getCategory();
        List<Commodity> list = mapper.getCommodityList();
        list = list.stream()
                .filter(o ->(commodityName == null || o.getCommodityName().contains(commodityName)) &&
                        (category == 0 || o.getCategory()==category))
                .collect(Collectors.toList());
        return new PageVo<>(pageBo, list);
    }

  /*  @Override
    public Result<String> addCommodity(CommodityRequestDTO request) {
        Commodity newCommodity = new Commodity();
        newCommodity.setCommodityName(request.getCommodityName());
        newCommodity.setCategory(request.getCategory());
        newCommodity.setPointsRequired(request.getPointsRequired());
        newCommodity.setStock(request.getStock());
        newCommodity.setDescription(request.getDescription());

        if(newCommodity!=null){
            if (mapper.insertCommodity(newCommodity) > 0) {
                return Result.ok("添加成功");
            } else {
                return Result.fail("添加失败");
            }
        }
        return Result.fail("屬性名爲空");
    }*/

    @Override
    public Result<String> updateCommodityList(CommodityRequestDTO request) {
        Commodity newCommodity = new Commodity();

        newCommodity.setCommodityId(request.getCommodityId());
        newCommodity.setCommodityName(request.getCommodityName());
        newCommodity.setCategory(request.getCategory());
        newCommodity.setPointsRequired(request.getPointsRequired());
        newCommodity.setStock(request.getStock());
        newCommodity.setDescription(request.getDescription());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime lastUpdatedTime = LocalDateTime.now();
        String format = lastUpdatedTime.format(formatter);
        newCommodity.setUpdatedAt(format);


        if(newCommodity!=null){
            mapper.updateCommodityList(newCommodity);
            return Result.ok("修改成功");
        }
        else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Commodity selectCommodityById(int id) {
        return mapper.selectCommodityById(id);
    }

    @Override
    public void placeCommodity(Commodity currentCommodity) {
        mapper.placeCommodity(currentCommodity);
    }

    @Override
    public Result<String> deleteCommodityList(Commodity commodity) {
        int id=commodity.getCommodityId();
        if(id!=0){
            mapper.deleteCommodityById(commodity);
            return Result.ok("删除成功");
        }else{
            return Result.error(400, "删除失败");
        }
    }

    @Override
    public void batchDeleteCommodityList(List<Commodity> commodityList) {
        mapper.deleteCommodityList(commodityList);
    }

    @Override
    public Commodity getById(int commodityId) {
        return mapper.selectImageUrl(commodityId);
    }

    @Override
    public PageVo<StudentPoints> getStudentPointsList(PageBo pageBo) {
        List<StudentPoints> logs = mapper.getStudentPointsList();
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<StudentPoints> searchStudentPointsList(StudentPointsRequestDTO request, PageBo pageBo) {
        int id=request.getStudentId();
        List<StudentPoints> list = mapper.getStudentPointsList();
        list = list.stream()
                .filter(o -> (id == 0 || o.getStudentId()==id))
                .collect(Collectors.toList());
        return new PageVo<>(pageBo, list);
    }

    @Override
    public Result<String> updatePointsList(StudentPointsRequestDTO request) {
        int studentId=request.getStudentId();
        int points=mapper.selectPointsById(studentId);
        int differencePoints=request.getPoints()-points;

        StudentPoints newStudent = new StudentPoints();

        newStudent.setStudentId(studentId);
        newStudent.setPoints(request.getPoints());
        if(differencePoints>0){
            newStudent.setTotalEarned(request.getTotalEarned()+differencePoints);
            newStudent.setTotalSpent(newStudent.getTotalEarned()-request.getPoints());
        }else{
            newStudent.setTotalSpent(request.getTotalSpent()-differencePoints);
            newStudent.setTotalEarned(newStudent.getTotalSpent()+request.getPoints());
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime lastUpdatedTime = LocalDateTime.now();
        String format = lastUpdatedTime.format(formatter);
        newStudent.setLastUpdated(format);

        if(newStudent!=null){
            mapper.updatePointsList(newStudent);
            return Result.ok("修改成功");
        }
        else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public PageVo<ExchangeRecord> getExchangeRecordList(PageBo pageBo) {
        List<ExchangeRecord> logs = mapper.getExchangeRecordList();
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<ExchangeRecord> searchExchangeRecordList(ExchangeRecordRequestDTO request, PageBo pageBo) {
        ExchangeRecord exchange=new ExchangeRecord();
        exchange.setStudentId(request.getStudentId());
        exchange.setCommodityId(request.getCommodityId());
        List<ExchangeRecord> logs = mapper.searchExchange(exchange);

        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<Order> getPendingOrderList(PageBo pageBo) {
        List<Order> logs = mapper.getPendingOrderList();
        for (Order order : logs) {
            int commodityId = order.getCommodityId();
            Commodity commodity = mapper.selectCommodityById(commodityId);
            if(commodity.getStock()>0) order.setRepertoryStatus(1);
            else order.setRepertoryStatus(0);
        }
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<Order> getShipedOrderList(PageBo pageBo) {
        List<Order> logs = mapper.getShipedOrderList();
        for (Order order : logs) {
            order.setRepertoryStatus(1);
        }
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<Order> getCompletedOrderList(PageBo pageBo) {
        List<Order> logs = mapper.getCompletedOrderList();
        for (Order order : logs) {
            order.setRepertoryStatus(1);
        }
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public PageVo<Order> getCanceledOrderList(PageBo pageBo) {
        List<Order> logs = mapper.getCanceledOrderList();
        for (Order order : logs) {
            order.setRepertoryStatus(1);
        }
        return new PageVo<>(pageBo, logs);
    }

    //學生id，商品id，狀態
    @Override
    public PageVo<Order> searchOrderList(OrderRequestDTO request, PageBo pageBo) {
        Order order=new Order();
        order.setOrderId(request.getOrderId());
        order.setStudentId(request.getStudentId());
        order.setCommodityId(request.getCommodityId());
        order.setStatus(request.getStatus());
        List<Order> logs = mapper.searchByOrder(request);

        return new PageVo<>(pageBo, logs);
    }


    @Override
    public Result<String> updateOrderList(OrderRequestDTO request) {
        Order nowOrder=mapper.selectOrderById(request.getOrderId());  //訂單當前狀態
        Order newOrder = setOredr(request);
        StudentPoints newStudent = mapper.selectStudentById(nowOrder.getStudentId());
        Commodity currentCommodity=mapper.selectCommodityById(nowOrder.getCommodityId());
        //1.取消訂單
        //如果還沒有發貨，取消訂單，將積分退還
        if(nowOrder.getStatus()==1&&newOrder.getStatus()==4){
            newStudent.setPoints(newStudent.getPoints()+nowOrder.getPointsUsed());
            newStudent.setTotalSpent(newStudent.getTotalSpent()-nowOrder.getPointsUsed());
            mapper.updatePointsList(newStudent);

            newOrder.setOrderDate(request.getOrderDate());  // 设置其他日期字段为null
            newOrder.setShipDate(request.getShipDate());
            newOrder.setCancelDate(format);

        }
        //如果還發貨，取消訂單，將積分退還，庫存更新
        if(nowOrder.getStatus()==2&&newOrder.getStatus()==4){
            newStudent.setPoints(newStudent.getPoints()+nowOrder.getPointsUsed());
            newStudent.setTotalSpent(newStudent.getTotalSpent()-nowOrder.getPointsUsed());
            mapper.updatePointsList(newStudent);

            currentCommodity.setStock(currentCommodity.getStock()+1);
            mapper.updateCommodityList(currentCommodity);

            newOrder.setOrderDate(request.getOrderDate());  // 设置其他日期字段为null
            newOrder.setShipDate(request.getShipDate());
            newOrder.setCancelDate(format);

        }
        //如果發貨，庫存更新
        if (newOrder.getStatus()==2) {
            currentCommodity.setStock(currentCommodity.getStock()-1);
            mapper.updateCommodityList(currentCommodity);

            newOrder.setShipDate(format);
            newOrder.setCancelDate(null);
            newOrder.setCompleteDate(null);
            newOrder.setOrderDate(request.getOrderDate());  // 设置其他日期字段为null
        }
        if (newOrder.getStatus()==3) {
            newOrder.setCancelDate(format);
            newOrder.setCompleteDate(null);
            newOrder.setOrderDate(request.getOrderDate());  // 设置其他日期字段为null
            newOrder.setShipDate(null);
        }

        if(newOrder!=null){
            mapper.updateOrderList(newOrder);
            return Result.ok("修改成功");
        }
        else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public List<OrderView> getOrderDataList(int orderId) {
        List<OrderView> logs = mapper.getOrderDataList(orderId);
        for (OrderView order : logs) {
            String url=order.getImageUrl();
            order.setImageUrl("http://seedling-classmate.oss-cn-beijing.aliyuncs.com/"+url);
            if(order.getStock()>0) order.setRepertoryStatus("库存充足");
            else order.setRepertoryStatus("库存不足");

            if(order.getProvince()!=null) order.setProvinceName(mapper.selectProvinceName(order.getProvince()));
            if(order.getCity()!=null) order.setCityName(mapper.selectCityName(order.getCity()));
            if(order.getArea()!=null) order.setAreaName(mapper.selectAreaName(order.getArea()));
            String cancelReasonStr = String.valueOf(order.getCancelReason());
            if (!cancelReasonStr.isEmpty()) {
                char firstChar = cancelReasonStr.charAt(0);
                if (firstChar == '1') {
                    order.setEditor("管理员");
                } else if (firstChar == '2') {
                    order.setEditor("学生");
                } else {
                    // 如果cancelReason不符合预期格式，可以设置默认值或其他逻辑
                    order.setEditor("未知");
                }
            }
        }
        return logs;
    }

    @Override
    public List<OrderTimeLineDTO> getTimeLineList(int orderId) {
        List<OrderTimeLineDTO> logs =new ArrayList<>();
        List<LocalDateTime> dates = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 根据实际日期字符串格式调整

        // 查询并转换日期
        String orderDateString = mapper.selectOrderDate(orderId);
        LocalDateTime orderDate = orderDateString != null ? LocalDateTime.parse(orderDateString, formatter) : null;
        dates.add(orderDate);

        String shipDateString = mapper.selectShipDate(orderId);
        LocalDateTime shipDate = shipDateString != null ? LocalDateTime.parse(shipDateString, formatter) : null;
        dates.add(shipDate);

        String cancelDateString = mapper.selectCancelDate(orderId);
        LocalDateTime cancelDate = cancelDateString != null ? LocalDateTime.parse(cancelDateString, formatter) : null;
        dates.add(cancelDate);

        String completeDateString = mapper.selectCompleteDate(orderId);
        LocalDateTime completeDate = completeDateString != null ? LocalDateTime.parse(completeDateString, formatter) : null;
        dates.add(completeDate);

        // 删除null值
        dates.removeIf(Objects::isNull);

        // 排序
        dates.sort(Comparator.naturalOrder());

        for (LocalDateTime date : dates) {
            String time = date.format(formatter);
            OrderTimeLineDTO orderTimeLineDTO = new OrderTimeLineDTO();
            orderTimeLineDTO.setTime(time); // 转换回字符串格式
            if(time.equals(orderDateString)) {
                orderTimeLineDTO.setStateName("订单创建");
                orderTimeLineDTO.setColor("#76cb02");
            } else if(time.equals(shipDateString)) {
                orderTimeLineDTO.setStateName("订单发货");
                orderTimeLineDTO.setColor("#76cb02");
            } else if(time.equals(cancelDateString)) {
                orderTimeLineDTO.setStateName("订单取消");
                orderTimeLineDTO.setColor("#F56C6C");
            } else if(time.equals(completeDateString)) {
                orderTimeLineDTO.setStateName("订单完成");
                orderTimeLineDTO.setColor("#76cb02");
            }
            logs.add(orderTimeLineDTO);
        }
        return logs;
    }

    @Override
    public Result<String> cancelOrder(Order newOrder) {
        Order nowOrder=mapper.selectOrderById(newOrder.getOrderId());  //訂單當前狀態
        StudentPoints newStudent = mapper.selectStudentById(nowOrder.getStudentId());
        Commodity currentCommodity=mapper.selectCommodityById(nowOrder.getCommodityId());


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime lastUpdatedTime = LocalDateTime.now();
        String format = lastUpdatedTime.format(formatter);

        //1.取消訂單
        //如果還沒有發貨，取消訂單，將積分退還
        if(nowOrder.getStatus()==1&&newOrder.getCanceled()==2){
            System.out.println("還沒有發貨：");
            System.out.println("1.退還積分：");
            newStudent.setPoints(newStudent.getPoints()+nowOrder.getPointsUsed());
            newStudent.setTotalSpent(newStudent.getTotalSpent()-nowOrder.getPointsUsed());
            mapper.updatePointsList(newStudent);
        }
        //如果還發貨，取消訂單，將積分退還，庫存更新
        if(nowOrder.getStatus()==2&&newOrder.getCanceled()==2){
            System.out.println("已經發貨：");
            //退還積分
            System.out.println("1.退還積分：");
            newStudent.setPoints(newStudent.getPoints()+nowOrder.getPointsUsed());
            newStudent.setTotalSpent(newStudent.getTotalSpent()-nowOrder.getPointsUsed());
            mapper.updatePointsList(newStudent);
            //庫存更新
            System.out.println("2.庫存更新：");
            currentCommodity.setStock(currentCommodity.getStock()+1);
            mapper.updateCommodityList(currentCommodity);
        }
        newOrder.setCancelDate(format);
        System.out.println("取消時間："+format);
        System.out.println("訂單狀態："+newOrder);
        if(newOrder!=null){
            mapper.cancelOrder(newOrder);
            return Result.ok("修改成功");
        }
        else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Result<String> deleteOrder(int orderId) {
        if(orderId!=0){
            mapper.deleteOrderById(orderId);
            return Result.ok("删除成功");
        }else{
            return Result.error(400, "删除失败");
        }
    }

    @Override
    public Result<String> shipOrder(Order newOrder) {
        Order nowOrder=mapper.selectOrderById(newOrder.getOrderId());  //訂單當前狀態
        StudentPoints newStudent = mapper.selectStudentById(nowOrder.getStudentId());
        Commodity currentCommodity=mapper.selectCommodityById(nowOrder.getCommodityId());


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime lastUpdatedTime = LocalDateTime.now();
        String format = lastUpdatedTime.format(formatter);

        //1.訂單發貨
        System.out.println("已經發貨：");
        //庫存更新
        System.out.println("2.庫存更新：");
        currentCommodity.setStock(currentCommodity.getStock()-1);
        mapper.updateCommodityList(currentCommodity);

        newOrder.setShipDate(format);
        System.out.println("訂單狀態："+newOrder);
        if(newOrder!=null){
            mapper.shipOrder(newOrder);
            return Result.ok("修改成功");
        }
        else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Result<String> addCommodity(Commodity curCommodity, String fileName) {
        curCommodity.setImageUrl(fileName);

        if(curCommodity!=null){
            if (mapper.addCommdity(curCommodity) > 0) {
                return Result.ok("添加成功");
            } else {
                return Result.fail("添加失败");
            }
        }
        return Result.fail("添加失败,填写内容为空");
    }

    @Override
    public Result<String> updateReceiverInfo(Order request) {
        if(request!=null){
            if (mapper.updateReceiverInfo(request) > 0) {
                return Result.ok("修改成功");
            } else {
                return Result.fail("修改失败");
            }
        }
        return Result.fail("修改失败,填写内容为空");
    }


    private Order setOredr(OrderRequestDTO request) {
        Order newOrder = new Order();
        newOrder.setOrderId(request.getOrderId());
        newOrder.setStudentId(request.getStudentId());
        newOrder.setCommodityId(request.getCommodityId());
        newOrder.setStatus(request.getStatus());
        newOrder.setOrderDate(request.getOrderDate());
        newOrder.setShipDate(request.getShipDate());
        newOrder.setCancelDate(request.getCancelDate());
        newOrder.setCompleteDate(request.getCompleteDate());
        newOrder.setAddress(request.getAddress());
        newOrder.setContactName(request.getContactName());
        newOrder.setContactPhone(request.getContactPhone());
        newOrder.setTrackingNumber(request.getTrackingNumber());
        newOrder.setPointsUsed(request.getPointsUsed());
        newOrder.setNotes(request.getNotes());

        return newOrder;
    }
}
